<?php

class Domain51_Service_Amazon_S3_Object extends Solar_Base
{
    private $_connection = null;
    
    public function __construct($config)
    {
        $this->_connection = $config['connection'];
    }
    
    public function put(Domain51_Service_Amazon_S3_Value_Object $object)
    {
        if (empty($object->bucket)) {
            // todo: switch out to Solar error code once I find it
            throw $this->_exception('ERR_BUCKET_NOT_SPECIFIED');
        }
        
        $headerObj = $this->_connection->getHeader();
        foreach ($object->headers as $headerKey => $headerValue) {
            $headerObj->add($headerKey, $headerValue);
        }
        $this->_connection->setHeader($headerObj);
        
        $fullName = $object->bucket . $object->name;
        $response = $this->_connection->doRequest(
            'PUT', 
            $object->fullName,
            $object->body
        );
        return $response->getResponseCode() == 200;
    }
    
    /**
     * @todo add support for extra request headers (see doc for full example):
     *      - If-Modified-Since
     *      - If-Unmodified-Since
     *      - If-Match
     *      - If-None-Match
     *      - Range
     */
    public function get($path) 
    {
        $response = $this->_connection->doRequest('GET', $path);
        if ($response->getResponseCode() != 200) {
            throw $this->_exception('ERR_FILE_NOT_FOUND');
        }
        
        $object = Solar::factory('Domain51_Service_Amazon_S3_Value_Object');
        $object->name = basename($path);
        $object->bucket = dirname($path);
        $object->body = $response->getBody();
        $object->headers = $response->getHeaders();
        
        return $object;
    }
    
    /**
     * @todo implement once Connection class can do HEAD requests
     */
    public function head($path) {
        $response = $this->_connection->doRequest('HEAD', $path);
        
        return $response->getHeaders();
    }
    
    /**
     *
     * Delete object
     *
     * NOTE: returns true even if the object didn't exist
     *
     */
    public function delete($path) {
        // strip out unwanted characters
        $path = preg_replace('/[^a-zA-Z0-9_\/-]/', '', $path);
        
        $response = $this->_connection->doRequest('DELETE', $path);
        return $response->getResponseCode() == '204';
    }
}

?>